<template>
    <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
import * as echarts from 'echarts'
import {isNotNull} from "@/utils/numberUtil";
import useResizeDom from '@/utils/useResizeDom.js'
const unwarp = (obj) => obj && (obj.__v_raw || obj.valueOf() || obj);
export default {
    props: {
        className: {
            type: String,
            default: 'chart'
        },
        width: {
            type: String,
            default: '100%'
        },
        height: {
            type: String,
            default: '80vh'
        },
        autoResize: {
            type: Boolean,
            default: true
        },
        chartData: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            chart: null,
            resizeObserver:useResizeDom(),
        }
    },
    watch: {
        chartData: {
            deep: true,
            handler(val) {
                this.setOptions(val)
            }
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.initChart()
        })
        this.resizeObserver.observe(this.$el,this.resizeChart)
       
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
    },
    methods: {
        initChart(options) {
            this.chart = echarts.init(this.$el, 'macarons')
            this.setOptions(options)
        },
        setOptions(options) {
            if (isNotNull(options)){
                unwarp(this.chart).setOption(options);
            }
        },
        resizeChart(){
            this.chart?.resize()
        }
    }
}
</script>
